package pub.tbc.toolkit.http;

import com.google.gson.Gson;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pub.tbc.toolkit.Loops;
import pub.tbc.toolkit.Objs;
import pub.tbc.toolkit.function.Consumer;

import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tbc tianbencai@e-eduspace.com
 * @version 1.0 {2015年11月17日 下午3:18:11}
 */
public abstract class AbstractHttpRequester {
    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 若不设Content-Type，则默认json
     */
    private String CONTENT_TYPE_DEFAULT = "application/json";
    private String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded;charset=utf-8";


    /**
     * URL预处理：若不是以 "http"开头，则添加"http://"
     *
     * @param url
     * @return http://+url
     * @author tbc tianbencai@e-eduspace.com
     * @version 1.0 {2015年11月17日 下午3:07:31}
     */
    protected String requestUrlInit(String url) {
        log.debug("request url = " + url);
        if (url.startsWith("http://") || url.startsWith("https://")) {
            return url;
        } else {
            log.debug("请求的URL无协议信息，默认自动添加[http://]");
            return "http://" + url;
        }
    }

    /**
     * 获取请求头
     *
     * @author tbc e-eduspace
     * @version 1.0 create:{2015年11月17日 下午11:49:35}
     */
    protected Header[] getHeaders(Header[] headers) {
        if (null != headers && headers.length > 0) {
            log.debug("request headers = " + Arrays.toString(headers));
            String contentType = null;
            for (Header header : headers) {
                String name = header.getName();
                if (HTTP.CONTENT_TYPE.equals(name.replaceAll(" ", ""))) {
                    contentType = header.getValue();
                    break;
                }
            }
            if (contentType == null) {
                headers[headers.length + 1] = new BasicHeader("Content-Type", CONTENT_TYPE_DEFAULT);
            }
            return headers;
        }
        // 否则 ，若请求头为空，添加默认
        return new BasicHeader[]{
                new BasicHeader("Content-Type", CONTENT_TYPE_DEFAULT),
                // 连接要关闭
                new BasicHeader("Connection", "close")};
    }

    /**
     * 获取请求体
     *
     * @author tbc e-eduspace
     * @version 1.0 create:{2015年11月17日 下午11:49:46}
     */
    protected HttpEntity getEntity(List<NameValuePair> httpBody, String contentType) {
        AbstractHttpEntity entity = null;
        if (Objs.nonEmpty(httpBody)) {
            // String contentType = httpParam.getContentType();
            if (null == contentType || CONTENT_TYPE_DEFAULT.equals(contentType.replaceAll(" ", "").toLowerCase())) {
                final Map<String, Object> map = new HashMap<>();
                Loops.forEach(httpBody, new Consumer<NameValuePair>() {
                    @Override
                    public void accept(NameValuePair nameValuePair) {
                        map.put(nameValuePair.getName(), nameValuePair.getValue());
                    }
                });
                try {
//					entity = new StringEntity(new Gson().toJson(map), CONTENT_TYPE_DEFAULT, HTTP.UTF_8);
                    entity = new StringEntity(new Gson().toJson(map), ContentType.APPLICATION_JSON);
                } catch (UnsupportedCharsetException e) {
                    log.error("entity=new StringEntity(json, APPLICATION_JSON),UnsupportedCharsetException");
                    log.error(e.getMessage());
                    return null;
                }
                log.debug("request body = " + entity);
                return entity;
            } else if (CONTENT_TYPE_FORM.equals(contentType.replaceAll(" ", "")) || CONTENT_TYPE_FORM.contains(contentType.replaceAll(" ", ""))) {
                entity = new UrlEncodedFormEntity(httpBody, Consts.UTF_8);
                log.debug("request body = " + entity);
                return entity;
            } else {
                log.info("不被支持的 Content-Type");
                return null;
            }
        }
        return null;
    }

}
